<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>PL/Perl Functions and Arguments</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.1.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="PL/Perl - Perl Procedural Language"
HREF="plperl.html"><LINK
REL="PREVIOUS"
TITLE="PL/Perl - Perl Procedural Language"
HREF="plperl.html"><LINK
REL="NEXT"
TITLE="Data Values in PL/Perl"
HREF="plperl-data.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-12-01T22:07:59"></HEAD
><BODY
CLASS="SECT1"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.1.2 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="PL/Perl - Perl Procedural Language"
HREF="plperl.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="plperl.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
>Chapter 41. PL/Perl - Perl Procedural Language</TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="Data Values in PL/Perl"
HREF="plperl-data.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="PLPERL-FUNCS"
>41.1. PL/Perl Functions and Arguments</A
></H1
><P
>   To create a function in the PL/Perl language, use the standard
   <A
HREF="sql-createfunction.html"
>CREATE FUNCTION</A
>
   syntax:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION <TT
CLASS="REPLACEABLE"
><I
>funcname</I
></TT
> (<TT
CLASS="REPLACEABLE"
><I
>argument-types</I
></TT
>) RETURNS <TT
CLASS="REPLACEABLE"
><I
>return-type</I
></TT
> AS $$
    # PL/Perl function body
$$ LANGUAGE plperl;</PRE
><P>

   The body of the function is ordinary Perl code. In fact, the PL/Perl
   glue code wraps it inside a Perl subroutine.  A PL/Perl function is
   called in a scalar context, so it can't return a list.  You can return
   non-scalar values (arrays, records, and sets) by returning a reference,
   as discussed below.
  </P
><P
>   PL/Perl also supports anonymous code blocks called with the
   <A
HREF="sql-do.html"
>DO</A
> statement:

</P><PRE
CLASS="PROGRAMLISTING"
>DO $$
    # PL/Perl code
$$ LANGUAGE plperl;</PRE
><P>

   An anonymous code block receives no arguments, and whatever value it
   might return is discarded.  Otherwise it behaves just like a function.
  </P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>    The use of named nested subroutines is dangerous in Perl, especially if
    they refer to lexical variables in the enclosing scope. Because a PL/Perl
    function is wrapped in a subroutine, any named subroutine you place inside
    one will be nested. In general, it is far safer to create anonymous
    subroutines which you call via a coderef. For more information, see the
    entries for <TT
CLASS="LITERAL"
>Variable "%s" will not stay shared</TT
> and
    <TT
CLASS="LITERAL"
>Variable "%s" is not available</TT
> in the
    <SPAN
CLASS="CITEREFENTRY"
><SPAN
CLASS="REFENTRYTITLE"
>perldiag</SPAN
></SPAN
> man page, or
    search the Internet for <SPAN
CLASS="QUOTE"
>"perl nested named subroutine"</SPAN
>.
   </P
></BLOCKQUOTE
></DIV
><P
>   The syntax of the <TT
CLASS="COMMAND"
>CREATE FUNCTION</TT
> command requires
   the function body to be written as a string constant.  It is usually
   most convenient to use dollar quoting (see <A
HREF="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING"
>Section 4.1.2.4</A
>) for the string constant.
   If you choose to use escape string syntax <TT
CLASS="LITERAL"
>E''</TT
>,
   you must double any single quote marks (<TT
CLASS="LITERAL"
>'</TT
>) and backslashes
   (<TT
CLASS="LITERAL"
>\</TT
>) used in the body of the function
   (see <A
HREF="sql-syntax-lexical.html#SQL-SYNTAX-STRINGS"
>Section 4.1.2.1</A
>).
  </P
><P
>   Arguments and results are handled as in any other Perl subroutine:
   arguments are passed in <TT
CLASS="VARNAME"
>@_</TT
>, and a result value
   is returned with <TT
CLASS="LITERAL"
>return</TT
> or as the last expression
   evaluated in the function.
  </P
><P
>   For example, a function returning the greater of two integer values
   could be defined as:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
    if ($_[0] &gt; $_[1]) { return $_[0]; }
    return $_[1];
$$ LANGUAGE plperl;</PRE
><P>
  </P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>      Arguments will be converted from the database's encoding to UTF-8
      for use inside PL/Perl, and then converted from UTF-8 back to the
      database encoding upon return.
    </P
></BLOCKQUOTE
></DIV
><P
>   If an SQL null value is passed to a function,
   the argument value will appear as <SPAN
CLASS="QUOTE"
>"undefined"</SPAN
> in Perl.  The
   above function definition will not behave very nicely with null
   inputs (in fact, it will act as though they are zeroes).  We could
   add <TT
CLASS="LITERAL"
>STRICT</TT
> to the function definition to make
   <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> do something more reasonable:
   if a null value is passed, the function will not be called at all,
   but will just return a null result automatically.  Alternatively,
   we could check for undefined inputs in the function body.  For
   example, suppose that we wanted <CODE
CLASS="FUNCTION"
>perl_max</CODE
> with
   one null and one nonnull argument to return the nonnull argument,
   rather than a null value:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
    my ($x, $y) = @_;
    if (not defined $x) {
        return undef if not defined $y;
        return $y;
    }
    return $x if not defined $y;
    return $x if $x &gt; $y;
    return $y;
$$ LANGUAGE plperl;</PRE
><P>
   As shown above, to return an SQL null value from a PL/Perl
   function, return an undefined value.  This can be done whether the
   function is strict or not.
  </P
><P
>   Anything in a function argument that is not a reference is
   a string, which is in the standard <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
>
   external text representation for the relevant data type. In the case of
   ordinary numeric or text types, Perl will just do the right thing and
   the programmer will normally not have to worry about it. However, in
   other cases the argument will need to be converted into a form that is
   more usable in Perl. For example, the <CODE
CLASS="FUNCTION"
>decode_bytea</CODE
>
   function can be used to convert an argument of
   type <TT
CLASS="TYPE"
>bytea</TT
> into unescaped binary.
  </P
><P
>   Similarly, values passed back to <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
>
   must be in the external text representation format. For example, the
   <CODE
CLASS="FUNCTION"
>encode_bytea</CODE
> function can be used to
   escape binary data for a return value of type <TT
CLASS="TYPE"
>bytea</TT
>.
  </P
><P
>   Perl can return <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> arrays as
   references to Perl arrays.  Here is an example:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE OR REPLACE function returns_array()
RETURNS text[][] AS $$
    return [['a&quot;b','c,d'],['e\\f','g']];
$$ LANGUAGE plperl;

select returns_array();</PRE
><P>
  </P
><P
>   Perl passes <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> arrays as a blessed
   PostgreSQL::InServer::ARRAY object. This object may be treated as an array
   reference or a string, allowing for backward compatibility with Perl
   code written for <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> versions below 9.1 to
   run.  For example:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$
    my $arg = shift;
    my $result = "";
    return undef if (!defined $arg);

    # as an array reference
    for (@$arg) {
        $result .= $_;
    }

    # also works as a string
    $result .= $arg;

    return $result;
$$ LANGUAGE plperl;

SELECT concat_array_elements(ARRAY['PL','/','Perl']);</PRE
><P>

  </P><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>    Multi-dimensional arrays are represented as references to
    lower-dimensional arrays of references in a way common to every Perl
    programmer.
   </P
></BLOCKQUOTE
></DIV
><P>
  </P
><P
>   Composite-type arguments are passed to the function as references
   to hashes.  The keys of the hash are the attribute names of the
   composite type.  Here is an example:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE TABLE employee (
    name text,
    basesalary integer,
    bonus integer
);

CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
    my ($emp) = @_;
    return $emp-&gt;{basesalary} + $emp-&gt;{bonus};
$$ LANGUAGE plperl;

SELECT name, empcomp(employee.*) FROM employee;</PRE
><P>
  </P
><P
>   A PL/Perl function can return a composite-type result using the same
   approach: return a reference to a hash that has the required attributes.
   For example:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);

CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
    return {f2 =&gt; 'hello', f1 =&gt; 1, f3 =&gt; 'world'};
$$ LANGUAGE plperl;

SELECT * FROM perl_row();</PRE
><P>

   Any columns in the declared result data type that are not present in the
   hash will be returned as null values.
  </P
><P
>    PL/Perl functions can also return sets of either scalar or
    composite types.  Usually you'll want to return rows one at a
    time, both to speed up startup time and to keep from queueing up
    the entire result set in memory.  You can do this with
    <CODE
CLASS="FUNCTION"
>return_next</CODE
> as illustrated below.  Note that
    after the last <CODE
CLASS="FUNCTION"
>return_next</CODE
>, you must put
    either <TT
CLASS="LITERAL"
>return</TT
> or (better) <TT
CLASS="LITERAL"
>return
    undef</TT
>.

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE OR REPLACE FUNCTION perl_set_int(int)
RETURNS SETOF INTEGER AS $$
    foreach (0..$_[0]) {
        return_next($_);
    }
    return undef;
$$ LANGUAGE plperl;

SELECT * FROM perl_set_int(5);

CREATE OR REPLACE FUNCTION perl_set()
RETURNS SETOF testrowperl AS $$
    return_next({ f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' });
    return_next({ f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' });
    return_next({ f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' });
    return undef;
$$ LANGUAGE plperl;</PRE
><P>

    For small result sets, you can return a reference to an array that
    contains either scalars, references to arrays, or references to
    hashes for simple types, array types, and composite types,
    respectively.  Here are some simple examples of returning the entire
    result set as an array reference:

</P><PRE
CLASS="PROGRAMLISTING"
>CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
    return [0..$_[0]];
$$ LANGUAGE plperl;

SELECT * FROM perl_set_int(5);

CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
    return [
        { f1 =&gt; 1, f2 =&gt; 'Hello', f3 =&gt; 'World' },
        { f1 =&gt; 2, f2 =&gt; 'Hello', f3 =&gt; 'PostgreSQL' },
        { f1 =&gt; 3, f2 =&gt; 'Hello', f3 =&gt; 'PL/Perl' }
    ];
$$ LANGUAGE plperl;

SELECT * FROM perl_set();</PRE
><P>
  </P
><P
>   If you wish to use the <TT
CLASS="LITERAL"
>strict</TT
> pragma with your code you
   have a few options. For temporary global use you can <TT
CLASS="COMMAND"
>SET</TT
>
   <TT
CLASS="LITERAL"
>plperl.use_strict</TT
> to true.
   This will affect subsequent compilations of <SPAN
CLASS="APPLICATION"
>PL/Perl</SPAN
>
   functions, but not functions already compiled in the current session.
   For permanent global use you can set <TT
CLASS="LITERAL"
>plperl.use_strict</TT
>
   to true in the <TT
CLASS="FILENAME"
>postgresql.conf</TT
> file.
  </P
><P
>   For permanent use in specific functions you can simply put:
</P><PRE
CLASS="PROGRAMLISTING"
>use strict;</PRE
><P>
   at the top of the function body.
  </P
><P
>  The <TT
CLASS="LITERAL"
>feature</TT
> pragma is also available to <CODE
CLASS="FUNCTION"
>use</CODE
> if your Perl is version 5.10.0 or higher.
  </P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="plperl.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="plperl-data.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>PL/Perl - Perl Procedural Language</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="plperl.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Data Values in PL/Perl</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>